// pages/games/tigger/tigger.js
const app = getApp();

Page({
  data: {
    userPoints: 100, // 用户积分
    isSpinning: false,
    isStopping: false,
    showResult: false,
    showNoPointsModal: false,
    showResultModal: false,
    currentReward: null,
    currentDisplayIcon: '',
    currentDisplayName: '',
    currentDisplayRarity: '',
    rewardsPool: [
      { id: 1, name: '小星星', icon: '⭐', description: '装饰用的小星星', rarity: 'common', rate: 45 },
      { id: 2, name: '爱心', icon: '❤️', description: '表达爱意的符号', rarity: 'common', rate: 30 },
      { id: 3, name: '彩虹', icon: '🌈', description: '美丽的彩虹', rarity: 'rare', rate: 15 },
      { id: 4, name: '钻石', icon: '💎', description: '闪闪发光的钻石', rarity: 'epic', rate: 8 },
      { id: 5, name: '皇冠', icon: '👑', description: '至高无上的皇冠', rarity: 'legendary', rate: 2 }
    ],
    confettiItems: [],
    isDarkMode: false
  },

  onLoad(options) {
    this.initPage();
    this.checkDarkMode();
  },

  onShow() {
    this.checkDarkMode();
  },

  // 初始化页面
  initPage() {
    // 从统一的userData获取积分
    const userData = wx.getStorageSync('userData') || {};
    this.setData({ userPoints: userData.points || 100 });
  },

  // 检查暗黑模式
  checkDarkMode() {
    const isDarkMode = wx.getStorageSync('darkMode') || false;
    this.setData({ isDarkMode });
  },

  // 开始扭蛋
  async drawEgg() {
    if (this.data.isSpinning || this.data.isStopping) return;
    
    if (this.data.userPoints < 1) {
      this.setData({ showNoPointsModal: true });
      return;
    }

    // 扣除积分
    const newPoints = this.data.userPoints - 1;
    this.setData({ userPoints: newPoints });
    const userData = wx.getStorageSync('userData') || {};
    userData.points = newPoints;
    wx.setStorageSync('userData', userData);

    // 计算奖励
    const reward = this.calculateReward();
    
    // 保存获得的奖励
    this.saveReward(reward);

    // 开始疯狂切换动画
    this.startRapidSwitch(reward);
  },

  // 优化后的动画逻辑，避免卡屏
  startRapidSwitch(finalReward) {
    this.setData({ isSpinning: true });
    
    const speeds = [
      { duration: 100, count: 15 },  // 快
      { duration: 200, count: 10 },  // 中速
      { duration: 300, count: 8 },   // 慢速
      { duration: 500, count: 5 }    // 很慢
    ];

    let currentSpeedIndex = 0;
    let currentCount = 0;
    let switchTimeout;
    let isAnimating = true;

    const performSwitch = () => {
      if (!isAnimating) return;

      const randomReward = this.data.rewardsPool[Math.floor(Math.random() * this.data.rewardsPool.length)];
      
      // 使用wx.nextTick确保UI更新同步
      wx.nextTick(() => {
        this.setData({
          currentDisplayIcon: randomReward.icon,
          currentDisplayName: randomReward.name,
          currentDisplayRarity: randomReward.rarity
        });
      });

      currentCount++;

      if (currentCount >= speeds[currentSpeedIndex].count) {
        currentSpeedIndex++;
        currentCount = 0;

        if (currentSpeedIndex < speeds.length) {
          switchTimeout = setTimeout(performSwitch, speeds[currentSpeedIndex].duration);
        } else {
          // 动画结束，显示最终结果
          isAnimating = false;
          
          wx.nextTick(() => {
            this.setData({
              isSpinning: false,
              isStopping: true,
              currentDisplayIcon: finalReward.icon,
              currentDisplayName: finalReward.name,
              currentDisplayRarity: finalReward.rarity,
              currentReward: finalReward
            });

            // 延迟显示结果弹窗
            setTimeout(() => {
              this.setData({ isStopping: false });
              this.showResultModal();
            }, 600);
          });
        }
      } else {
        switchTimeout = setTimeout(performSwitch, speeds[currentSpeedIndex].duration);
      }
    };

    // 开始第一轮切换
    switchTimeout = setTimeout(performSwitch, speeds[0].duration);

    // 清理定时器
    this.clearAnimationTimer = () => {
      isAnimating = false;
      if (switchTimeout) {
        clearTimeout(switchTimeout);
      }
    };
  },

  // 页面卸载时清理定时器
  onUnload() {
    if (this.clearAnimationTimer) {
      this.clearAnimationTimer();
    }
  },

  // 显示结果弹窗
  showResultModal() {
    // 生成彩带数据
    const colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7', '#DDA0DD'];
    const confettiItems = Array.from({ length: 20 }, () => ({
      left: Math.random() * 100,
      top: Math.random() * 100,
      color: colors[Math.floor(Math.random() * colors.length)],
      delay: Math.random() * 2
    }));

    this.setData({
      showResultModal: true,
      confettiItems
    });
  },

  // 关闭结果弹窗
  closeResultModal() {
    this.setData({ showResultModal: false });
  },

  // 再来一次
  playAgain() {
    this.setData({ showResultModal: false });
    this.drawEgg();
  },

  // 计算奖励
  calculateReward() {
    const random = Math.random() * 100;
    let cumulativeRate = 0;

    for (const reward of this.data.rewardsPool) {
      cumulativeRate += reward.rate;
      if (random <= cumulativeRate) {
        return reward;
      }
    }

    // 默认返回第一个奖励
    return this.data.rewardsPool[0];
  },

  // 保存获得的奖励
  saveReward(reward) {
    const rewards = wx.getStorageSync('collectedRewards') || [];
    rewards.push({
      ...reward,
      timestamp: Date.now()
    });
    wx.setStorageSync('collectedRewards', rewards);
  },

  // 重置机器
  resetMachine() {
    this.setData({
      showResultModal: false,
      currentReward: null,
      currentDisplayIcon: '',
      currentDisplayName: '',
      currentDisplayRarity: ''
    });
  },

  // 关闭积分不足提示
  closeNoPointsModal() {
    this.setData({ showNoPointsModal: false });
  },

  // 防止事件冒泡
  preventClose() {
    // 空函数，用于阻止事件冒泡
  },

  // 添加积分（测试用）
  addTestPoints() {
    const newPoints = this.data.userPoints + 10;
    this.setData({ userPoints: newPoints });
    wx.setStorageSync('userPoints', newPoints);
    
    wx.showToast({
      title: '获得10积分',
      icon: 'success'
    });
  },

  // 查看收集的奖励
  viewCollectedRewards() {
    wx.navigateTo({
      url: '/pages/games/tigger/rewards'
    });
  },

  // 分享功能
  onShareAppMessage() {
    return {
      title: '来玩幸运扭蛋机！',
      path: '/pages/games/tigger/tigger',
      imageUrl: '/images/egg-machine.png'
    };
  }
});